﻿using System;
using System.Collections.Generic;
using OBoobsWallpaper.Configuration;
using OBoobsWallpaper.Entity;

namespace OBoobsWallpaper.Logic
{
    public interface IRssCache
    {
        List<RssItem> GetLastElements();
        void Push(List<RssItem> rssItems);
    }

    public class RssCache : IRssCache
    {
        private readonly IRssCacheConfig config;
        private readonly List<RssItem> items = new List<RssItem>(0);

        public RssCache(IRssCacheConfig config)
        {
            this.config = config;
        }

        public List<RssItem> GetLastElements()
        {
            Trim();
            return items;
        }

        public void Push(List<RssItem> rssItems)
        {
            items.AddRange(rssItems);
            Trim();
        }

        private void Trim()
        {
            for (int i = 0; i < items.Count; i++)
                if (DateTime.UtcNow - items[i].Date > config.MaxRssItemAge)
                    items.RemoveAt(i);
            while(items.Count > 0 && items.Count > config.MaxElements)
                items.RemoveAt(0);
        }
    }
}